package ssn.common.view;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class DownloadView extends AbstractView {

	protected Log log = LogFactory.getLog(this.getClass());

	@SuppressWarnings("rawtypes")
	@Override
	protected void renderMergedOutputModel(Map model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		File file       = (File) model.get("file");

		// 브라우저 체크
		String fileName = null;
		boolean ieResult = request.getHeader("User-Agent").indexOf("MSIE") > -1;
		if (ieResult) {
			fileName = URLEncoder.encode((String)model.get("fileName"), "UTF-8");
		} else {
			fileName = new String(((String)model.get("fileName")).getBytes("UTF-8"), "ISO-8859-1");
		}

		response.setContentType("application/x-download");
		response.setContentLength((int) file.length());
		response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\";");
		response.setHeader("Content-Transfer-Encoding", "binary");

		BufferedInputStream  fileIn  = null;
		BufferedOutputStream fileOut = null;

        try
        {
			fileIn  = new BufferedInputStream(new FileInputStream(file));
			fileOut = new BufferedOutputStream(response.getOutputStream());
			FileCopyUtils.copy(fileIn, fileOut);

		} catch (Exception e) {
			log.debug(e.getMessage());
		} finally {
			if (fileIn != null) {
				try {
					fileIn.close();
				} catch (Exception e) {
					log.debug(e.getMessage());
				}
			}
			if (fileOut != null) {
				try {
					fileOut.close();
				} catch (Exception e) {
					log.debug(e.getMessage());
				}
			}
		}
	}

}
